package cn.stylefeng.guns.modular.cb.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.cb.entity.CbResumeDelivery;
import cn.stylefeng.guns.modular.cb.mapper.CbResumeDeliveryMapper;
import cn.stylefeng.guns.modular.cb.model.params.*;
import cn.stylefeng.guns.modular.cb.model.result.*;
import cn.stylefeng.guns.modular.cb.service.*;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ss
 * @since 2021-01-19
 */
@Service
public class CbResumeDeliveryServiceImpl extends ServiceImpl<CbResumeDeliveryMapper, CbResumeDelivery> implements CbResumeDeliveryService {

    private static Logger logger = LoggerFactory.getLogger(CbResumeDeliveryServiceImpl.class);

    @Autowired
    private CbMessagesService cbMessagesService;

    @Autowired
    private CbPositionService cbPositionService;

    @Autowired
    private CbCustomerStaffService cbCustomerStaffService;
    @Autowired
    private CbCustomerStudentsService cbCustomerStudentsService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private OSSService ossService;

    @Override
    public void add(CbResumeDeliveryParam param){
        CbResumeDelivery entity = getEntity(param);
        this.save(entity);
        param.setId(entity.getId());

    }

    @Override
    public void delete(CbResumeDeliveryParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(CbResumeDeliveryParam param){
        CbResumeDelivery oldEntity = getOldEntity(param);
        CbResumeDelivery newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public CbResumeDeliveryResult findBySpec(CbResumeDeliveryParam param){
        return null;
    }

    @Override
    public List<CbResumeDeliveryResult> findListBySpec(CbResumeDeliveryParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(CbResumeDeliveryParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 职位投递列表
     * @param positionId
     * @return
     */
    @Override
    public LayuiPageInfo findDeliverList(Long positionId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findDeliverList(pageContext, positionId);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 每日新增投递统计
     * @param startDate
     * @param countArr
     * @return
     */
    @Override
    public List<Map<String, Object>> queryDateCount(String startDate, String[] countArr) {
        return this.baseMapper.queryDateCount(startDate, countArr);
    }

    private Serializable getKey(CbResumeDeliveryParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private CbResumeDelivery getOldEntity(CbResumeDeliveryParam param) {
        return this.getById(getKey(param));
    }

    private CbResumeDelivery getEntity(CbResumeDeliveryParam param) {
        CbResumeDelivery entity = new CbResumeDelivery();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /********重构********/

    @Override
    public void addResumeDelivery(CbResumeDeliveryParam cbResumeDeliveryParam) {
        LoginUser user = LoginContextHolder.getContext().getUser();
        try {
            CbPositionResult positionResult = cbPositionService.getCbPositionDetail(cbResumeDeliveryParam.getPositionId());
            if(positionResult==null){
                ResponseData.error("该职位不存在");
            }
            //职位中投递数量+1
            Integer resumeCount = positionResult.getResumeCount();
            if (StringUtils.isEmpty(resumeCount)){
                resumeCount = 0;
            }
            CbPositionParam cbp = new CbPositionParam();
            cbp.setId(positionResult.getId());
            cbp.setResumeCount(resumeCount+1);
            this.cbPositionService.update(cbp);//修改职位被投递数量

            this.add(cbResumeDeliveryParam);//添加投递记录

            CbCustomerCompanyParam cbCustomerCompanyParam = new CbCustomerCompanyParam();
            cbCustomerCompanyParam.setId(cbResumeDeliveryParam.getCompanyId());

            /***********************发送邮件***********************/
            //获取对方邮箱
            String toEmail = positionResult.getEmail();
            //获取发送方姓名/简历
            CbCustomerStudentsParam studentParam = new CbCustomerStudentsParam();
            studentParam.setCreateUser(user.getId());
            CbCustomerStudentsResult studentsResult = cbCustomerStudentsService.getStudent(studentParam);
            if (studentsResult==null){
                ResponseData.error("投递人不存在");
            }
            //发送简历
            String resumePath = ossService.downloadFile(cbResumeDeliveryParam.getResume());
            if (StringUtils.isEmpty(resumePath)){
                ResponseData.error("简历不存在");
            }

            //获取内推人
            String staffName = "";
            Long staffId = cbResumeDeliveryParam.getStaffId();
            if (!StringUtils.isEmpty(staffId)){
                CbCustomerStaffParam staffParam = new CbCustomerStaffParam();
                staffParam.setId(staffId);
                CbCustomerStaffResult staff = cbCustomerStaffService.getStaff(staffParam);
                if (!StringUtils.isEmpty(staff)) {
                    staffName = "-" +staff.getName();
                }
            }
            //简历标题 岗位名称+推荐人姓名+候选人姓名+候选人电话号码
            String title = positionResult.getName() + staffName + "-" + studentsResult.getName() + "-" +studentsResult.getPhone();
            String content = "来自"+studentsResult.getName()+"的简历，请查收";
            emailService.sendAttachmentsMail(toEmail,title, content,resumePath);
//            Files.delete(Paths.get(resumePath));

            /***********************发送完成***********************/

            /***********************发送消息（企业和推荐人）***********************/
            Long id = cbResumeDeliveryParam.getId();
            //简历投递后添加一条消息数据给企业
            CbMessagesParam cbMessagesParam = new CbMessagesParam();
            cbMessagesParam.setSendUserid(studentsResult.getId());//消息发送人——普通用户
            cbMessagesParam.setMessageUserid(cbResumeDeliveryParam.getCompanyId());
            cbMessagesParam.setType(0L);
            cbMessagesParam.setMessage("您收到一条新的简历投递消息");
            cbMessagesParam.setStatus(0L);
            cbMessagesParam.setEventid(cbResumeDeliveryParam.getId());
            cbMessagesService.add(cbMessagesParam);
            if(cbResumeDeliveryParam.getStaffId()!=null&&cbResumeDeliveryParam.getStaffId()!=0){
                //简历投递后给推荐人发送一条消息
                cbMessagesParam = new CbMessagesParam();
                cbMessagesParam.setSendUserid(studentsResult.getId());//消息发送人——普通用户
                cbMessagesParam.setMessageUserid(cbResumeDeliveryParam.getStaffId());
                cbMessagesParam.setType(0L);
                cbMessagesParam.setMessage("您收到一条新的简历投递消息");
                cbMessagesParam.setStatus(0L);
                cbMessagesParam.setEventid(cbResumeDeliveryParam.getId());
                cbMessagesService.add(cbMessagesParam);
            }
        }catch (Exception e) {
            logger.error("resume delivery error: ", e);
        }
    }

    /**
     * 是否已经投递
     * @param paramCondition
     * @return
     */
    @Override
    public Integer getCountByUser(CbResumeDeliveryParam paramCondition) {
        return this.baseMapper.getCountByUser(paramCondition);
    }
}
